<template>
	<el-dialog class="abow-dialog" :visible.sync="visible" :top="playId?'2vh':'5vh'"
		:title="merge ? '合并短剧' : !playId ? '添加短剧' : '修改短剧'" :close-on-click-modal="false"
		:close-on-press-escape="false" width="650px">
		<el-dialog class="innerDialog" v-dialogDrag="innerCoverDialogDragFn" showScale custom-class="innerCoverDialog"
		      width="650px" :close-on-click-modal="false" :close-on-press-escape="false"
		      :title="innerTitle+'  '+innerTitleType"
		      :visible.sync="innerCoverVisible"
		      append-to-body @close="innerCloseFn">
			  <div class="d-flex a-cneter j-center">
				  <el-image :style="{width: innerCoverBodyWidth+'px',height: innerCoverBodyHeight+'px'}" :src="clickImg" fit="contain"></el-image>
			  </div>
		</el-dialog>
		<el-form class="form" :model="dataForm" :rules="dataRule " ref="dataForm" label-width="150px" size="medium" :inline="false"
			labelSuffix="：">
			<el-form-item prop="name" label="短剧名称">
				<el-input  clearable v-model="dataForm.name" placeholder="短剧名称" />
			</el-form-item>
			<el-form-item prop="alias_name" label="短剧别名">
				<el-input clearable v-model="dataForm.alias_name" placeholder="短剧别名" />
			</el-form-item>
			<el-form-item  prop="merge_playlet_id" v-if="merge"  label="合并短剧" >
				<el-select v-model="dataForm.merge_playlet_id" :multiple-limit=2 multiple placeholder="请选择">
					<el-option
					v-for="item2 in videoList"
					:key="item2.value"
					:label="item2.label"
					:value="item2.value">
					</el-option>
				</el-select>
				<!-- <div>提示：合并短剧顺序和上面选择后的顺序一直</div> -->
			</el-form-item>
			
	
			<el-form-item prop="cover" label="短剧封面图">
				<div class="d-flex">
					<img v-if="dataForm.cover" class="d-flex mr-20 pointer" :src="dataForm.cover" @click.stop="lookImg(dataForm.cover,'封面图')"
						style="width: 80px;height: auto;border-radius: 5px;">
					<div class="d-flex a-center">
						<el-button style="width: 80px;height: 40px;" v-if="$hasPermission('playlet:sts:uploadPath')"
							@click="uploadBtnFn('coverFileBtn','cover')">上传</el-button>
						<input type="file" ref="coverFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'images',0.9)" />
					</div>
				</div>
			</el-form-item>
			<el-form-item prop="thumbnail" label="短剧缩略图">
				<div class="d-flex">
					<img v-if="dataForm.thumbnail" class="d-flex mr-20 pointer" :src="dataForm.thumbnail" @click.stop="lookImg(dataForm.cover,'封面图')"
						style="width: 80px;height: auto;border-radius: 5px;">
					<div class="d-flex a-center">
						<el-button style="width: 80px;height: 40px;" v-if="$hasPermission('playlet:sts:uploadPath')"
							@click="uploadBtnFn('thumbnailFileBtn','thumbnail')">上传</el-button>
						<input type="file" ref="thumbnailFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'images',1)" />
					</div>
				</div>
			</el-form-item>
		
			<el-form-item prop="introduction" label="简介" style="height: 150px;" >
				<el-input
					type="textarea"
					placeholder="请输入内容"
					v-model="dataForm.introduction"
					maxlength="100"
					show-word-limit
					>
				</el-input>
			</el-form-item>
			<el-form-item prop="pay_type" label="支付类型">
				<el-select clearable v-model="dataForm.pay_type" placeholder="请选择">
					<el-option v-for="(item,index) in payType" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="dataForm.pay_type==2" prop="amount" label="价格">
				<el-input type="number" clearable v-model="dataForm.amount" placeholder="价格" />
			</el-form-item>
			<el-form-item v-if="playId" prop="last_episode_number" label="最后一集集数">
				<el-input type="number" clearable v-model="dataForm.last_episode_number" placeholder="最后一集集数" />
			</el-form-item>
			<el-form-item v-if="playId" prop="pay_start_cid" label="剧集收费">
				<el-select clearable v-model="dataForm.pay_start_cid" placeholder="请选择">
					<el-option v-for="(item,index) in allEpisodeList" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item v-if="playId && dataForm.playlet_type !=2 " prop="producer" label="制作方">
				<el-input clearable v-model="dataForm.producer" placeholder="制作方" />
			</el-form-item>

			<el-form-item v-if="playId && dataForm.playlet_type !=2" prop="registration_number" label="剧目备案号">
				<el-input clearable v-model="dataForm.registration_number" placeholder="剧目备案号" />
			</el-form-item>

			<el-form-item v-if="playId && dataForm.playlet_type !=2" prop="registration_number_url" label="剧目播放授权材料图片">
				<div class="d-flex">
					<img v-if="dataForm.registration_number_url" class="d-flex mr-20 pointer" :src="dataForm.registration_number_url" @click.stop="lookImg(dataForm.registration_number_url,'剧目播放授权材料图')"
						style="width: 80px;height: auto;border-radius: 5px;">
					<div class="d-flex a-center">
						<el-button style="width: 80px;height: 40px;" v-if="$hasPermission('playlet:sts:uploadPath')"
							@click="uploadBtnFn('registrationFileBtn','registration_number_url')">上传</el-button>
						<input type="file" ref="registrationFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'images',1)" />
					</div>
				</div>
			</el-form-item>
		
			<el-form-item v-if="!merge && dataForm.playlet_type != 2" label="抖音标签" >
				<el-select v-model="dataForm.tag_ids" :multiple-limit=3 multiple placeholder="请选择">
					<el-option
					v-for="item2 in tagList"
					:key="item2.value"
					:label="item2.label"
					:value="item2.value">
					</el-option>
				</el-select>
			</el-form-item>

			
			<div v-if="dataForm.playlet_type==1  && playId" style="display: flex;" >
				<el-form-item  label="演员1">
				<el-select clearable v-model="dataForm.actorList[0].actor_id" placeholder="请选择" > 
					<el-option v-for="(item,index) in actorList" :key="index" :label="item.label" :disabled="   dataForm.actorList[1] &&  item.value == dataForm.actorList[1].actor_id" :value="item.value"></el-option>
				</el-select>
				</el-form-item>
				<el-form-item  label="角色">
					<el-input clearable v-model="dataForm.actorList[0].role_name" placeholder="角色" />
				</el-form-item>
			</div>

			<div v-if="dataForm.playlet_type==1 && playId" style="display: flex;">
				<el-form-item  label="演员2">
				<el-select clearable v-model="dataForm.actorList[1].actor_id" placeholder="请选择"> 
					<el-option v-for="(item,index) in actorList" :key="index" :label="item.label" :disabled=" dataForm.actorList[0] && item.value == dataForm.actorList[0].actor_id" :value="item.value"></el-option>
				</el-select>
				</el-form-item>
				<el-form-item  label="角色">
					<el-input clearable v-model="dataForm.actorList[1].role_name" placeholder="角色" />
				</el-form-item>
			</div>



			
			<el-form-item prop="is_finish" label="是否完结">
				<el-select clearable v-model="dataForm.is_finish" placeholder="请选择">
					<el-option v-for="(item,index) in finish" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item prop="status" label="状态">
				<el-select clearable v-model="dataForm.status" placeholder="请选择">
					<el-option v-for="(item,index) in status" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('views.public.confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
	let that;
	import {
		debounce
	} from 'lodash'
	import {
		isEmail,
		isMobile
	} from '@/libs/validate'
	import schema from 'async-validator'
	import uploadTools from "./uploadTools";
	export default {
		mixins: [uploadTools],
		data() {
		
			return {
				videoList:[],
				merge:false,
				innerCoverBodyWidth:650,
				innerCoverBodyHeight:450,
				tagList:[],
				actorList:[],
				playId:null,
				field: '',
				innerTitle:'',
				innerTitleType:'',
				innerCoverVisible:false,
				showimagesProgress: false,
				showvideosProgress: false,
				clickImg:'',
				payType:[
				{
					value:1,
					label:'免费',
				},
				{
					value:2,
					label:'章节付费',
				}],
				finish:[
				{
					value:0,
					label:'未完结',
				},
				{
					value:1,
					label:'完结',
				}],
				status:[
				{
					value:0,
					label:'禁用',
				},
				{
					value:1,
					label:'正常',
				}],
				visible: false,
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				roleList: [],
				roleIdListDefault: [],
				allEpisodeList:[],
				dataForm: {
					playlet_type:1,
					merge_playlet_id:[],//合并列表
					name: '', //剧集名称
					alias_name:'',
					cover:'',//短剧封面图
					thumbnail:'',//缩略图
					introduction:'',//简介
					amount:'',//价格
					pay_type:1,//支付类型
					producer:'',//制作方
					is_finish:0,//是否完结，默认0未完结,1完结
					status: 1, //状态
					tag_ids:[],
					actorList:[{actor_id:'',role_name:""},{actor_id:'',role_name:""}]
					
				}
			}
		},
		created() {},
		mounted() {
			that = this;
			this.gettagList()
			this.getactorList()
			
			
		},
		computed: {
			dataRule() {
				return {
					merge_playlet_id:[{
							required: true,
							
							validator:(rule, value, callback) => {
						
								if (value.length<2) {
								return callback(new Error('合并短剧不能少于两部'));
								}else{
									callback();
								}
								
							},
							trigger: ['blur','change']
						}
					],
					name: [{
							required: true,
							message: '剧集名称不能为空!',
							trigger: ['blur','change']
						}
					],
					cover: [{
							required: true,
							message: '短剧封面图不能为空!',
							trigger: ['blur','change']
						}
					],
					thumbnail: [{
							required: true,
							message: '缩略图不能为空!',
							trigger: ['blur','change']
						}
					],
					amount: [{
							required: true,
							message: '价格不能为空!',
							trigger: ['blur','change']
						}
					],
					introduction: [{
							required: true,
							message: '简介不能为空!',
							trigger: ['blur','change']
						}
					],
					is_finish: [{
							required: true,
							message: '是否完结不能为空!',
							trigger: ['blur','change']
						}
					],
					tagig: [{
						required: true,
						message: '标签不能为空!',
						trigger: ['blur','change']
					}],
					status: [{
						required: true,
						message: '状态不能为空!',
						trigger: ['blur','change']
					}],
					actor: [{
						required: true,
						message: '演员不能为空!',
						trigger: ['blur','change']
					}],
					role: [{
						required: true,
						message: '角色不能为空!',
						trigger: ['blur','change']
					}]
				}
			}
		},
		watch:{
			'dataForm.pay_type'(newValue){
				if(!this.playId&&newValue==2){
					this.$set(this.dataForm, 'amount', '');
				}
			}
		},
		methods: {

			innerCoverDialogDragFn(e){
				if(e){
					if(e.bodywidth){
						this.innerCoverBodyWidth = e.bodywidth;
					}
					if(e.bodyheight){
						this.innerCoverBodyHeight = e.bodyheight;
					}
				}
			},
			innerCloseFn(){
				if(this.$refs.canvas){
					// 清除canvas元素和上下文的引用
					const canvas = this.$refs.canvas;
					const context = canvas.getContext('2d');
					context.clearRect(0, 0, canvas.width, canvas.height);
					// 删除canvas元素的事件监听器
					canvas.removeEventListener('click', this.handleClick);
					// 删除对canvas元素的引用
					canvas.parentNode.removeChild(canvas);
				}
			},
			async gettagList(){
				const tagList = await this.$axios.get(`/api/common/tag`);
				this.tagList = tagList
				console.log(270,tagList)
			},
			async getactorList(){
				const actorList = await this.$axios.get(`/api/common/actor`);
				this.actorList = actorList
				console.log(344,actorList)
			},
			//获取剧集集数
			async episodeFn(init=true){
				const episodeRes = await this.$axios.get(`/api/playlet/playlet/episodes/${this.playId}`);
				console.log(episodeRes);
				if(Array.isArray(episodeRes)){
					if(episodeRes.length){
						this.allEpisodeList = episodeRes;
						return;
					}
				}
				this.allEpisodeList = [];
			},
			lookImg(clickImg,type) {
				const dragDom = document.getElementsByClassName('innerCoverDialog');
				if(dragDom&&dragDom[0]){
					dragDom[0].style.width = '650px';
					dragDom[0].style.height = '514px';
				}
				this.innerCoverBodyWidth = 650;
				this.innerCoverBodyHeight = 450;
				this.clickImg = clickImg;
				this.innerTitleType = type||'';
				this.innerCoverVisible = true;
			},
			// compressNum压缩质量 范围0-1
			// async getFiles(event, fileType) {
			// 	this['show' + fileType + 'Progress'] = false;
			// 	console.log(event);
			// 	const files = event.target.files;
			// 	console.log(files);
			// 	if (files.length) {
			// 		const file = files[0];
			// 		let checkRes = false;

			// 		if (fileType == 'images') {
			// 			checkRes = this.checkPicFile(file, 10);
			// 			this.uploadBefore(file, fileType, checkRes);
			// 		} else if (fileType == 'videos') {
			// 			checkRes = this.checkVideoFile(file, 500);
			// 			this.uploadBefore(file, fileType, checkRes); 
			// 		}
			// 	}

			// 	event.target.value = '';
			// },
			async getFiles(event, fileType,compressNum=0.9) {
				this['show' + fileType + 'Progress'] = false;
				console.log(event);
				const files = event.target.files;
				console.log(files);
				if (files.length) {
					const file = files[0];
					let checkRes = false;
					//图片
					if (fileType == 'images') {
						// 压缩图片后再上传
						const reader = new FileReader();
						reader.onload = (e) => {
							const img = new Image();
							img.onload = () => {
								const canvas = document.createElement('canvas');
								const ctx = canvas.getContext('2d');
								const maxWidth = 800; // 压缩后的最大宽度
								const maxHeight = 800; // 压缩后的最大高度
								let width = img.width;
								let height = img.height;
								// 如果宽度和高度超过最大值，则等比例缩放
								if (width > maxWidth || height > maxHeight) {
									const aspectRatio = width / height;
									if (width > height) {
										width = maxWidth;
										height = maxWidth / aspectRatio;
									} else {
										width = maxHeight * aspectRatio;
										height = maxHeight;
									}
								}
								canvas.width = width;
								canvas.height = height;
								ctx.drawImage(img, 0, 0, width, height);
								const compressedDataURL = canvas.toDataURL('image/jpeg',compressNum); // 压缩后的图片数据URL，第二个参数表示压缩质量（0-1）
								// 将数据URL转换为Blob对象
								const blob = this.dataURLtoBlob(compressedDataURL);
								// 创建一个新的File对象
								const compressedFile = new File([blob], 'compressed_image.jpg', { type: 'image/jpeg' });
								// 在这里进行后续操作，上传压缩后的图片
								console.warn('压缩质量：',compressNum);
								console.warn('压缩后的图片',compressedFile);
								//检查文件格式和大小
								checkRes = this.checkPicFile(compressedFile, 10);
								this.uploadBefore(compressedFile,fileType,checkRes);
							};
							img.src = e.target.result;
						};
						reader.readAsDataURL(file);
					} else if (fileType == 'videos') {
						//视频
						checkRes = this.checkVideoFile(file, 500);
						this.uploadBefore(file,fileType,checkRes);
					}
				}
				event.target.value = '';
			},
			dataURLtoBlob(dataURL) {
				const byteString = atob(dataURL.split(',')[1]);
				const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
				const ab = new ArrayBuffer(byteString.length);
				const ia = new Uint8Array(ab);
				for (let i = 0; i < byteString.length; i++) {
					ia[i] = byteString.charCodeAt(i);
				}
				return new Blob([ab], {
					type: mimeString
				});
			},
			//获取上传密钥和文件路径再上传
			uploadBefore(file,fileType,checkRes){
				if (checkRes) {
					this.$axios.post(`/playlet/sts/uploadPath`, {
						type: fileType,
						suffix:this.getFileName(file.name)
					}).then(stsRes=>{
						if (typeof stsRes == 'object' && stsRes != null) {
							this.createOss(stsRes.token);
							this.handleUpload(file, fileType, stsRes.file_path + stsRes.file_name);
						}else{
							this.$message({
								message: '上传失败！',
								type: 'error',
								duration: 1500
							})
						}
					})
				}
			},
			handleUpload(file,fileType,uploadPath) {
				console.log('handleUploadhandleUpload');
				// 获取文件的后缀名
				// let objName = getFileNameUUID()
				var obj = file.name;
				var index = obj.lastIndexOf(".");
				obj = obj.substring(index, obj.length);
				// 生成的文件名，保留文件后缀名，进行拼接      
				let objName = this.getFileNameUUID() + this.getFileName(file.name);
				// 分片上传文件
				console.log(this.client);
				console.log(uploadPath);
				console.log(file);
				this.client.multipartUpload(`${uploadPath}`, file,{
					progress: async function(p) {
						that['show'+fileType+'Progress'] = true;
						that.percentage = Math.floor(p * 100);
					}
				}).then(clientRes => {
					console.log(clientRes, 'res')
					if(typeof clientRes == 'object' && clientRes!=null){
						if(typeof clientRes.res == 'object' && clientRes.res!=null){
							if(Array.isArray(clientRes.res.requestUrls)){
								if(clientRes.res.requestUrls.length){
									let requestUrl = this.removeUrlParams(clientRes.res.requestUrls[0]);
									if(!requestUrl){
										return this.$message({
											message: '上传失败！链接为空',
											type: 'error',
											duration: 1500
										})
									}
									if(fileType == 'images'){
										this.$set(this.dataForm, this.field, requestUrl);
									}else if(fileType == 'videos'){
										let video_cover = requestUrl+"?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto";
										console.log(requestUrl);
										this.$set(this.dataForm, this.field, requestUrl);
										console.log(this.dataForm);
										this.videoOptions.video.url = requestUrl;
										this.videoOptions.video.pic = video_cover;
									}
									this.$refs.dataForm.validateField(this.field);
									this['show'+fileType+'Progress'] = false;
									return this.$message({
										message: '上传成功！',
										type: 'success',
										duration: 1500
									})
								}
							}
						}
					}
					this['show'+fileType+'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				}).catch(err=>{
					console.log(err);
					this['show'+fileType+'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				})
			},
			uploadBtnFn(fileBtn, field) {
				console.log(502, fileBtn, field)
				this.field = field;
				this.$refs[fileBtn].click();
			},
			async init() {
				this.visible = true;
				this.dataForm.tag_ids = [46];
				// this.dataForm = {
				// 	merge_playlet_id:[],//合并列表
				// 	name: '', //剧集名称
				// 	cover:'',//短剧封面图
				// 	thumbnail:'',//缩略图
				// 	introduction:'',//简介
				// 	amount:'',//价格
				// 	pay_type:1,//支付类型
				// 	producer:'',//制作方
				// 	is_finish:0,//是否完结，默认0未完结,1完结
				// 	status: 1, //状态
				// 	tag_ids:[46]
				// }
	
				if(this.merge){
					const videoList = await this.$axios.get(`/api/common/playletOrdinary`);
					this.videoList = videoList
					console.log(484,videoList)
				}
				
				this.$nextTick(() => {
					console.log('initinitinitinitinitinit');
					this.$refs.dataForm.resetFields();
				})
			},
			update(row) {
				// this.dataForm = {
				// 	merge_playlet_id:[],//合并列表
				// 	name: '', //剧集名称
				// 	cover:'',//短剧封面图
				// 	thumbnail:'',//缩略图
				// 	introduction:'',//简介
				// 	amount:'',//价格
				// 	pay_type:1,//支付类型
				// 	producer:'',//制作方
				// 	is_finish:0,//是否完结，默认0未完结,1完结
				// 	status: 1, //状态
				// 	tag_ids:[46]
				// }
			
				console.log(616,row)
				this.visible = true;
				this.episodeFn();
				this.$nextTick(() => {
					console.log(531,this.$refs.dataForm)
					// if(this.$refs.dataForm != undefined){
						this.$refs.dataForm.resetFields();
					// }
					
					
					this.dataForm = Object.assign({}, row);

				})
			},
			diypost(){
				this.$axios.post(this.merge? `/api/playlet/playlet/mergePlaylet` : this.playId?`/api/playlet/playlet/update/${this.playId}`:'/api/playlet/playlet/create', this.dataForm).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 1200,
							onClose: () => {
								this.visible = false;
								this.$emit('refreshDataList');
							}
						})
					}).catch(() => {})
			},
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				console.log('表单提交',this.dataForm,this.$refs.dataForm.validate());
				this.$refs.dataForm.validate((valid) => {
					console.log(valid + '--+++++-----------')
					if (!valid) {
						return false
					}
					if(this.dataForm.tag_ids.length==0 && this.dataForm.playlet_type!=2){
						return this.$message({
						message: '请选择抖音标签！',
						type: 'error',
						duration: 1500
					})
					}
					if(this.merge){
						let diylist = this.videoList;
						
						let onename = null ;
						let two =null; 
						diylist.forEach((element,index) => {
							if(element.value == this.dataForm.merge_playlet_id[0]){
								onename = element.label
							}else if(element.value == this.dataForm.merge_playlet_id[1]){
								two = element.label
							}
							
						});
						this.$confirm(`合并第一部剧为：${onename}，第二部剧为：${two}`, '提示', {
							confirmButtonText: this.$t('views.public.confirm'),
							cancelButtonText: this.$t('views.public.cancel'),
							type: 'warning'
						}).then(() => {
							this.diypost()
						}).catch(() => {})
					}else{
						this.diypost()
					}
					

					console.log(478,this.dataForm);
		
					
				})
			}, 1000, {
				leading: true,
				trailing: false
			})
		}
	}
</script>

<style lang="scss" scoped>
	.form{
		width: 540px;
	}
	.innerDialog :deep(.el-dialog__header){
		padding: 20px!important;
	}
	.innerDialog :deep(.el-dialog__body){
		padding: 0px!important;
	}
	.innerDialog :deep(.el-dialog__headerbtn){
		font-size: 25px!important;
	}
	:deep(.el-textarea__inner){
		min-height: 140px !important;
		max-height: 140px !important;
	}
</style>